package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.Orderservice;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;


import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderMobileController {

    @Reference
    private Orderservice orderservice;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("add")
    public Result add(@RequestBody Map map) {
        try {
            String telephone = (String) map.get("telephone");

            String key = telephone + RedisMessageConstant.SENDTYPE_ORDER;

            String redisCode = jedisPool.getResource().get(key);

            String code = (String) map.get("validateCode");

            if (code == null || !code.equals(redisCode)) {
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            } else {
                Order order = orderservice.add(map);

                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, ValidateCodeUtils.generateValidateCode(4).toString());

                return new Result(true, MessageConstant.ADD_ORDER_SUCCESS, order);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());


        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_ORDER_FAIL);
        }
    }

    @RequestMapping("findById")
    public Result findById(@RequestParam("id") Integer id) {
        try {
            Map map = orderservice.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }

}
